package com.test;

import java.util.*;
import java.util.Map.Entry;

public class TimeListener {
	private volatile HashMap<String, Long> schedule = new HashMap<String, Long>();
	private Thread thread;
	private volatile boolean flag;

	/**
	 * 优化方案:1.用数组,长度为22222222222包含所有手机号
	 * 2.新建map数组,长度为60,每秒清空一次
	 * 3.不删除,修改has()方法超时则判断不存在
	 */
	public TimeListener() {
		thread = new Thread(new Runnable() {
			public void run() {
				long now = 0;
				while (flag) {
					Thread.yield();
					now = System.currentTimeMillis();
					Iterator<Entry<String,Long>> iter=schedule.entrySet().iterator();
					for (Entry<String, Long> entry=null;iter.hasNext();) {//有风险
						entry=iter.next();
						if (entry.getValue() - now < 0) // 过期删除
							iter.remove();
					}
				}
			}
		});
	}

	public void store(String msg, long millisecond) {
		long now = System.currentTimeMillis();
		schedule.put(msg, now + millisecond);
	}

	public void listening() {
		this.flag = true;
		thread.setDaemon(true);
		thread.start();
	}

	public boolean has(String str) {
		if (schedule.containsKey(str))
			return true;
		else
			return false;
	}

	public void stop() {
		this.flag = false;
	}

	public static void main(String[] args) throws InterruptedException {
		TimeListener tListener = new TimeListener();
		TimeListener t = new TimeListener();
		t.listening();
		tListener.listening();
		t.store("kdfj", 463);
		t.store("kd3fj", 463);
		t.store("kd2fj", 463);
		t.store("kd1fj", 463);
		t.store("kd14fj", 463);
		t.store("kd15fj", 463);
		t.store("kd1f5j", 463);
		t.store("k5j", 3333);
		Thread.sleep(1111);
System.out.println(t.has("kdfj"));
		System.out.println(t.has("k5j"));
	}
}
